package com.StarStudio.Service.Impl;

import cn.hutool.core.util.IdUtil;
import com.StarStudio.DAO.GoodsDAO;
import com.StarStudio.DAO.PanicBuyingGoodsDAO;
import com.StarStudio.DAO.PanicBuyingOrdersDAO;
import com.ruoyi.common.core.Entity.Goods;
import com.ruoyi.common.core.Entity.MessageConstant;
import com.ruoyi.common.core.Entity.PanicBuyingGoods;
import com.StarStudio.Service.PanicBuyingGoodsService;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
public class PanicBuyingGoodsServiceImpl implements PanicBuyingGoodsService {

    @Autowired
    PanicBuyingGoodsDAO panicBuyingGoodsDAO;

    @Autowired
    GoodsDAO goodsDAO;

    @Autowired
    RedisService redisService;

    @Autowired
    PanicBuyingOrdersDAO panicBuyingOrdersDAO;

    @Override
    public List<PanicBuyingGoods> findPanicBuyingGoodsList(PanicBuyingGoods panicBuyingGoods) {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (sysUser == null){
            throw new RuntimeException(MessageConstant.USER_NO_EXIST);
        }
        List<PanicBuyingGoods> panicBuyingGoodsList;
        if (sysUser.isAdmin()){
            panicBuyingGoodsList = panicBuyingGoodsDAO.findPanicBuyingGoodsList(panicBuyingGoods);
            if (panicBuyingGoodsList != null && panicBuyingGoodsList.size() > 0){
                for (PanicBuyingGoods buyingGoods : panicBuyingGoodsList) {
                    Goods goods = goodsDAO.findByGoods_id(buyingGoods.getGoods_id());
                    Map<String,Object> param = new HashMap<>();
                    param.put("goodsName",goods.getGoods_name());
                    buyingGoods.setParams(param);
                }
            }
        }else {
            panicBuyingGoodsList = panicBuyingGoodsDAO.findPanicBuyingGoodsListByStoreId(panicBuyingGoods,sysUser.getUserId());
            if (panicBuyingGoodsList != null && panicBuyingGoodsList.size() > 0){
                for (PanicBuyingGoods buyingGoods : panicBuyingGoodsList) {
                    Goods goods = goodsDAO.findByGoods_id(buyingGoods.getGoods_id());
                    Map<String,Object> param = new HashMap<>();
                    param.put("goodsName",goods.getGoods_name());
                    buyingGoods.setParams(param);
                }
            }
        }
        return panicBuyingGoodsList;
    }

    @Override
    public List<PanicBuyingGoods> findPanicBuyingGoodsList1(PanicBuyingGoods panicBuyingGoods) {
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsDAO.findPanicBuyingGoodsList(panicBuyingGoods);
        if (panicBuyingGoodsList != null && panicBuyingGoodsList.size() > 0){
            for (PanicBuyingGoods buyingGoods : panicBuyingGoodsList) {
                Goods goods = goodsDAO.findByGoods_id(buyingGoods.getGoods_id());
                Map<String,Object> param = new HashMap<>();
                param.put("goodsName",goods.getGoods_name());
                buyingGoods.setParams(param);
            }
        }
        return panicBuyingGoodsList;
    }

    @Override
    public long findTotalRecord() {
        return panicBuyingGoodsDAO.findTotalRecord();
    }

    @Override
    public PanicBuyingGoods findByGoods_id(long goods_id) {
        return panicBuyingGoodsDAO.findByGoods_id(goods_id);
    }

    @Override
    public List<PanicBuyingGoods> PanicBuyingGoodsList() {
        return panicBuyingGoodsDAO.PanicBuyingGoodsList();
    }

    @Override
    public int updatePanicBuyingGoods(PanicBuyingGoods panicBuyingGoods) {
        int new_pb_goods_stock = panicBuyingGoods.getPanic_buying_goods_stock();
        int old_pb_goods_stock = panicBuyingGoodsDAO.findByPanic_buying_goods_stockByPanic_buying_goods_id(panicBuyingGoods.getPanic_buying_goods_id());
        if (new_pb_goods_stock != old_pb_goods_stock){
            Goods byGoods_id = goodsDAO.findByGoods_id(panicBuyingGoods.getGoods_id());
            int totalStock = byGoods_id.getStock() + old_pb_goods_stock;
            if (new_pb_goods_stock > old_pb_goods_stock){ /* 商品库存增加 */
                if (new_pb_goods_stock <= totalStock){
                    byGoods_id.setStock(totalStock - new_pb_goods_stock);
                }else {
                    throw new RuntimeException("商品库存不足！");
                }
            }else { /* 商品库存减少 */
                if (new_pb_goods_stock >= 0){
                    byGoods_id.setStock(totalStock - new_pb_goods_stock);
                }else {
                    throw new RuntimeException("库存不能小于零！");
                }
            }
            goodsDAO.updateGoods(byGoods_id);
        }
        return panicBuyingGoodsDAO.updatePanicBuyingGoods(panicBuyingGoods);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void AddPanicBuyingGoods(PanicBuyingGoods panicBuyingGoods) {
        int panic_buying_goods_stock = panicBuyingGoods.getPanic_buying_goods_stock();
        Goods byGoods_id = goodsDAO.findByGoods_id(panicBuyingGoods.getGoods_id());
        if (byGoods_id.getStock() >= panic_buying_goods_stock){
            byGoods_id.setStock(byGoods_id.getStock() - panic_buying_goods_stock);
            goodsDAO.updateGoods(byGoods_id);
            panicBuyingGoods.setDel_flag(false);
            panicBuyingGoods.setPanic_buying_goods_id(IdUtil.getSnowflakeNextId()); //使用雪花ID
            panicBuyingGoodsDAO.AddPanicBuyingGoods(panicBuyingGoods);
        }else {
            throw new RuntimeException("商品库存不足！");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void DeletePanicBuyingGoods(long panic_buying_goods_id) {
        //删除抢购商品时，把库存归还到对应的普通商品库存中
        int pbg_stock = panicBuyingGoodsDAO.findByPanic_buying_goods_stockByPanic_buying_goods_id(panic_buying_goods_id);
        long goodsId = panicBuyingGoodsDAO.findGoodsIdByPBGId(panic_buying_goods_id);
        int OldStock = goodsDAO.findStockByGoodsId(goodsId);
        goodsDAO.updateGoodsStockById(goodsId,OldStock + pbg_stock);
        //逻辑删除抢购商品
        panicBuyingGoodsDAO.DeletePanicBuyingGoods(panic_buying_goods_id);
    }

    /**
     * 获取抢购商品对应的商品ID集合
     * @return 商品ID集合
     * @Author ChengLee
     * @Date 2023/01/08
     */
    @Override
    public List<Long> getGoodsIdListFromPanicBuyingGoods() {
        return panicBuyingGoodsDAO.getGoodsIdListFromPanicBuyingGoods();
    }

    @Override
    public long findStoreTotalRecord(Long storeId) {
        return panicBuyingGoodsDAO.findStoreTotalRecord(storeId);
    }

    @Override
    public Long findGoodsIdByRecordId(Long panicBuyingGoodsId) {
        return panicBuyingGoodsDAO.findGoodsIdByRecordId(panicBuyingGoodsId);
    }

    /**
     * 每 30秒更新抢购商品状态
     */
    @Scheduled(cron = "*/30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void AutoUpdatePanicBuyingStatus(){
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsDAO.PanicBuyingGoodsList();
        if (!CollectionUtils.isEmpty(panicBuyingGoodsList)){
            for (PanicBuyingGoods panicBuyingGoods : panicBuyingGoodsList) {
                int status;
                if (new Timestamp(new Date().getTime()).before(panicBuyingGoods.getPanic_buying_start_time())){
                    status = 0;
                }else if (new Timestamp(new Date().getTime()).after(panicBuyingGoods.getPanic_buying_end_time())){
                    status = 2;
                    //获取对应普通商品,将抢购商品库存归还到对应的普通商品库存
                    Goods goods = goodsDAO.findByGoods_id(panicBuyingGoods.getGoods_id());
                    goods.setStock(goods.getStock() + panicBuyingGoods.getPanic_buying_goods_stock());
                    goodsDAO.updateGoods(goods);
                    //将抢购商品库存归 0
                    PanicBuyingGoods update = new PanicBuyingGoods();
                    BeanUtils.copyProperties(panicBuyingGoods,update);
                    update.setPanic_buying_goods_stock(0);
                    panicBuyingGoodsDAO.updatePanicBuyingGoods(update);
                }else {
                    status = 1;
                }
                panicBuyingGoodsDAO.updatePanicBuyingGoodsStatus(panicBuyingGoods.getPanic_buying_goods_id(), status);
            }
        }
    }

    /**
     * 每天00:00:00删除Redis中的抢购商品多余数据
     * @Author ChengLee
     * @Date 2023/05/22 
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void ClearRedisRedundantData(){
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsDAO.PanicBuyingEndStatusGoodsList();
        if (!CollectionUtils.isEmpty(panicBuyingGoodsList)){
            for (PanicBuyingGoods panicBuyingGoods : panicBuyingGoodsList) {
                //如果抢购已结束，删除Redis中该商品相关数据  1.抢购商品数据  2.抢购订单数据
                //panic_buying_goods:1266
                redisService.deleteObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id());
                //panic_buying_goods_order:188725:1654494768216039424
                //查询该抢购商品对应订单的用户ID
                List<Long> userIdList = panicBuyingOrdersDAO.findUserIdListByGoodsId(panicBuyingGoods.getGoods_id());
                if (!CollectionUtils.isEmpty(userIdList)){
                    for (Long userId : userIdList) {
                        redisService.deleteObject("panic_buying_goods_order:" + userId + ":" + panicBuyingGoods.getGoods_id());
                    }
                }
            }
        }
    }
}
